from bson import ObjectId
from flask import Blueprint,request,jsonify
from setting import MONGODB,RET

user = Blueprint("user",__name__)

@user.route("/reg",methods=["POST"])
def reg():
	user_info = request.form.to_dict()
	if user_info.get("gender") == "1":
		user_info["avatar"] = "mama.jpg"
	else:
		user_info["avatar"] = "baba.jpg"

	user_info["bind_toys"] = []
	user_info["friend_list"] = []

	"""
	{
		'username': 'qwe',
	 	'password': '76d80224611fc919a5d54f0ff9fba446', 
	 	'nickname': 'aaa', 
	 	'gender': '2'
	 	"avatar":"baba.jpg"
	 }
	"""

	MONGODB.users.insert_one(user_info)

	RET["CODE"] = 0
	RET["MSG"] = "注册成功"
	RET["DATA"] = {}

	return jsonify(RET)


@user.route("/login",methods=["POST"])
def login():
	"""
	{
		"username":username,
		"password":password
	}
	:return:
	{
		"code":0,
		"msg":"登录成功",
		"data":
		{
			"_id" : "5c8f582f268d7942f44c6703",
			"username" : "DragonFire",
			"gender" : "2",
			"nickname" : "厉害了我的哥",
			"avatar" : "baba.jpg",
			"friend_list" : [],
			"bind_toy" : []
		}
	}
	"""
	user_info = request.form.to_dict()
	userinfo = MONGODB.users.find_one(user_info)
	if not userinfo:
		pass

	userinfo["_id"] = str(userinfo.get("_id"))

	RET["CODE"] = 0
	RET["MSG"] = "登录成功"
	RET["DATA"] = userinfo

	return jsonify(RET)

@user.route("/auto_login",methods=["POST"])
def auto_login():
	user_id = request.form.get("_id")
	user_id = ObjectId(user_id)

	userinfo = MONGODB.users.find_one({"_id":user_id})
	if not userinfo:
		pass

	userinfo["_id"] = str(userinfo.get("_id"))

	RET["CODE"] = 0
	RET["MSG"] = "登录成功"
	RET["DATA"] = userinfo

	return jsonify(RET)